package controllers

import (
	"go-scripts/handler"
	"gopkg.in/mgo.v2"
	"go-scripts/models"
	"go-scripts/common"
	"errors"
	"gopkg.in/mgo.v2/bson"
	"strings"
	"fmt"
)

var effectController *EffectController

type EffectController struct {
	effectTopicDao *mgo.Collection
	topInfoDao *mgo.Collection
	tmpNewsDao *mgo.Collection
}
//初始化controller
func GetEffectController() *EffectController {
	if effectController != nil {
		return effectController
	}
	effectController = new(EffectController)
	var err error
	model := models.GetModel()
	effectController.effectTopicDao,err = model.GetModelCollection("EffectTopic")
	effectController.topInfoDao, err = model.GetModelCollection("TopInfo")
	effectController.tmpNewsDao, err = model.GetModelCollection("TmpNews")
	if err != nil {
		logger.Fatal(err)
	}
	return effectController
}
//删除主题
func (e *EffectController) RemoveEffectTopic(app *handler.Global)  {
	r := app.Request
	w := app.ResponseWriter
	hylandaId := r.FormValue("hylandaId")
	err := common.CloseOneTopic(hylandaId)
	app.CheckErr(err)
	err = common.DeleteOneTopic(hylandaId, e.effectTopicDao)
	app.CheckErr(err)
	SendJson(w, map[string]interface{}{
		"msg": "ok",
		"text": "remove success",
		"status": 200,
	})
}
//创建主题
func (e *EffectController) CreateEffectTopic(app *handler.Global)  {
	r := app.Request
	topInfoId :=r.FormValue("topInfoId")
	tmpNewsId := r.FormValue("tmpNewsId")
	fmt.Println(topInfoId, tmpNewsId)
	if topInfoId == "" || tmpNewsId == "" {
		app.NewError(400, errors.New("param missing"))
	}
	tmpNew := new(models.TmpNews)
	e.tmpNewsDao.Find(bson.M{
		"_id": bson.ObjectIdHex(tmpNewsId),
	}).One(tmpNew)
	fmt.Println(trans2Name(tmpNew.Stocks))
	fmt.Println(trans2Name(tmpNew.Themes))
	err := common.CreateTopInfoTopic(tmpNew.Title, topInfoId, trans2Name(tmpNew.Stocks), trans2Name(tmpNew.Themes), "topInfo", "", e.effectTopicDao)
	app.CheckErr(err)
	app.SendJson(map[string]interface{}{
		"status": 200,
		"msg": "create ok",
	})
}

func trans2Name(values []string) []string {
	names := []string{}
	for _, v := range values {
		if v != "" {
			ret := strings.Split(v, ",")
			if len(ret) > 1 {
				names = append(names, ret[1])
			}
		}
	}
	return names
}
//修改主题关键词
func (e *EffectController) UpdateEffectTopic(app *handler.Global)  {
	r := app.Request
	r.ParseForm()
	hylandaId := r.Form["hylandaId"][0]
	stockStr := r.Form["stocks"][0]
	themeStr := r.Form["themes"][0]
	stocks := strings.Split(stockStr, ",")
	themes := strings.Split(themeStr, ",")
	if (stockStr == "" && themeStr == "") || hylandaId == "" {
		app.NewError(400, errors.New("param error"))
	}

	//logger.Info(hylandaId, len(stocks), len(themes))
	err := common.UpdateOneTopic(hylandaId, stocks, themes)
	app.CheckErr(err)
	app.SendJson(map[string]interface{}{
		"status": 200,
		"msg": "update ok",
	})
}